import { Component } from 'react';
import { View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { AtDivider } from 'taro-ui';
import { getServiceList } from '@/service/apis/service/index';
import { checkAuth } from '@/utils/authUtil';
import SearchBar from '@/components/SearchBar';
import EmptyContent from '@/components/EmptyContent';
import globalStore from '@/store/global';
import ServiceItem from '@/components/ServiceItem';
import SkuModal from '@/components/SkuModal';
import Labels from './components/Labels/index';
import './index.scss';

export default class Index extends Component {
  state = {
    searchValue: '',
    // serviceList: [],
    currentList: [],
    currentService: {},
    skuModalShow: false,
    searched: false,
    skuInfo: {
      imageUrl: '',
      goodsName: '',
      price: 0,
      id: 1,
      count: 1,
      number: 0,
    },
    skuList: [],
    currentCate: 0,
    cateList: [],
  };
  serviceList: [];
  cateServices: {};
  allService: [];

  componentDidShow() {
    this.getServiceList();
  }

  getServiceList = async () => {
    try {
      const { data } = await getServiceList({
        store_name: globalStore.currentShop.store_name,
        way: '全部',
      });
      let cateList: any = [];
      if (data.services_cats) {
        let all: any = {
          id: 0,
          name: '所有分类',
        };
        let other = data.services_cats.map((item: string, key: number) => {
          return {
            id: key + 1,
            name: item,
          };
        });
        console.log('data', data);
        cateList = [all, ...other];
      }
      this.setState({
        currentList: data.services_all_list,
        cateList: cateList,
      });
      this.serviceList = data.services_all_list;
      this.allService = data.services_all_list;
      this.cateServices = data.services_cat_list;
      console.log('data', data);
    } catch (err) {
      console.log('err', err);
      Taro.showToast({
        title: err.message,
        icon: 'none',
      });
    }
  };

  onSelectSku = (service: any) => {
    console.log('service', service);
    let defaultSku = {};
    if (service.products.length > 0) {
      defaultSku = {
        id: service.products[0].id,
        price: service.products[0].vip_price,
        number: service.products[0].number,
        imageUrl: service.products[0].url,
      };
    }
    this.setState({
      currentService: service,
      skuInfo: {
        imageUrl: service.pic_url,
        goodsName: service.goods_name,
        price: service.min_price,
        count: 1,
        ...defaultSku,
      },
      skuList: service.products.map((item: any) => {
        return {
          id: item.id,
          name: item.specifications,
          price: item.vip_price,
          number: item.number,
          imageUrl: item.url,
        };
      }),
      skuModalShow: true,
    });
  };

  onHandle = (id: number) => {
    Taro.navigateTo({
      url: '/pages/appointment/detail/index?id=' + id,
    });
  };

  onSearchChange = (value: string) => {
    this.setState({
      searchValue: value,
      searched: !!value,
    });
    if (value) {
      this.filterData(value);
    } else {
      this.setState({
        searched: false,
        currentList: this.serviceList,
      });
    }
  };

  filterData = (value?: string) => {
    let _value = value || this.state.searchValue;
    const filterList = this.serviceList.filter(
      (item) => item.goods_name.indexOf(_value) !== -1 || item.brief.indexOf(_value) !== -1,
    );
    this.setState({
      currentList: filterList,
      searched: true,
    });
  };

  onHandleAddCart = (goods: any) => {
    console.log('goods: ', goods);
    this.setState({
      skuModalShow: true,
    });
  };

  onChangeSku = (sku) => {
    console.log('sku', sku);
    this.setState({
      skuInfo: {
        ...this.state.skuInfo,
        ...sku,
      },
    });
  };
  onSkuCountChange = (count: number) => {
    console.log('count', count);
    this.setState({
      skuInfo: {
        ...this.state.skuInfo,
        count,
      },
    });
  };
  onSkuSubmit = () => {
    console.log(this.state.skuInfo);
    const { skuInfo, currentService } = this.state;
    console.log('skuInfo: ', skuInfo);
    checkAuth(() => {
      Taro.navigateTo({
        url: `/subPages/service/submit/index?id=${currentService.id}&skuId=${skuInfo.id}&count=${skuInfo.count}`,
      });
    });
  };

  changeCate = (id: number) => {
    const currentCate: any = this.state.cateList.filter(
      (item: any) => Number(item.id) === Number(id),
    );
    console.log('currentCate', currentCate);
    if (currentCate.length > 0) {
      const cateName = currentCate[0].name;
      if (cateName === '所有分类') {
        console.log('333333', currentCate[0].name, this.allService);
        this.serviceList = this.allService;
      } else {
        this.serviceList = this.cateServices[cateName];
      }
      this.filterData();
    }
  };

  render() {
    const {
      searchValue,
      currentList,
      skuModalShow,
      skuInfo,
      skuList,
      cateList,
      currentCate,
      searched,
    } = this.state;
    return (
      <View className="appointment-container">
        <SearchBar
          searchValue={searchValue}
          placeholder="搜索您喜欢的服务吧"
          onChange={this.onSearchChange}
        />
        <View className="tab-list">
          <Labels active={currentCate} onChange={this.changeCate} list={cateList} />
          <View className="service-list">
            {currentList.map((service) => {
              return (
                <ServiceItem
                  key={service.id}
                  serviceInfo={service}
                  onHandle={this.onHandle}
                  onSelectSku={this.onSelectSku}
                />
              );
            })}
            {
              currentList.length !== 0 && <AtDivider content="~没有更多了~" fontColor="#aaa" lineColor="transparent" />
            }
            {currentList.length === 0 &&
              (searched ? (
                <EmptyContent title="暂未搜索到相关服务" />
              ) : (
                <EmptyContent title="暂无服务" />
              ))}
          </View>
        </View>
        {/* <CartBtn /> */}
        <SkuModal
          show={skuModalShow}
          type="service"
          showNumber={false}
          skuList={skuList}
          skuInfo={skuInfo}
          onChangeSku={this.onChangeSku}
          onCountChange={this.onSkuCountChange}
          onSubmit={this.onSkuSubmit}
          onClose={() => {
            this.setState({
              skuModalShow: false,
            });
          }}
        />
      </View>
    );
  }
}
